#include "DirectInput.h"

#pragma comment(lib,"dinput.lib")
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")

DirectInput::DirectInput()
{
	m_lpDInput8 = NULL;
	m_lpKeyboardDevice8 = NULL;
	m_lpMouseDevice8 = NULL;

	memset(m_keyState,0,sizeof(m_keyState));
	memset(&m_kMouseState,0,sizeof(m_kMouseState));
}

DirectInput::~DirectInput()
{
}

bool DirectInput::Initialize(void* hInstance)
{
	if(FAILED(DirectInput8Create((HINSTANCE)hInstance,DIRECTINPUT_VERSION,IID_IDirectInput8,(void**) &m_lpDInput8,NULL)))
	{
		return false;
	}

	if(FAILED(m_lpDInput8->CreateDevice(GUID_SysKeyboard,&m_lpKeyboardDevice8,NULL)))
	{
		return false;
	}	

	if(FAILED(m_lpDInput8->CreateDevice(GUID_SysMouse,&m_lpMouseDevice8,NULL)))
	{
		return false;
	}
	
	return true;
}

bool DirectInput::SetCooperativeLevel(HWND hHand)
{
	if(FAILED(m_lpKeyboardDevice8->SetCooperativeLevel(hHand,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
	{
		return false;
	}


	if(FAILED(m_lpKeyboardDevice8->SetDataFormat(&c_dfDIKeyboard)))
	{
		return false;
	}

	if(FAILED(m_lpKeyboardDevice8->Acquire()))
	{
		return false;
	}

	if(FAILED(m_lpMouseDevice8->SetCooperativeLevel(hHand,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
	{
		return false;
	}

	if(FAILED(m_lpMouseDevice8->SetDataFormat(&c_dfDIMouse)))
	{
		return false;
	}

	if(FAILED(m_lpMouseDevice8->Acquire()))
	{
		return false;
	}

	return true;
}

bool DirectInput::GetDeviceState()
{
	if(FAILED(m_lpKeyboardDevice8->GetDeviceState(sizeof(m_keyState),(LPVOID)&m_keyState)))
	{
		return false;
	}

	if(FAILED(m_lpMouseDevice8->GetDeviceState(sizeof(m_kMouseState),(LPVOID)&m_kMouseState)))
	{
		return false;
	}

	return true;
}

bool DirectInput::Finalize()
{
	if(m_lpKeyboardDevice8)
	{
		m_lpKeyboardDevice8->Unacquire();
		m_lpKeyboardDevice8->Release();
	}
	m_lpKeyboardDevice8 = NULL;

	if(m_lpMouseDevice8)
	{
		m_lpMouseDevice8->Unacquire();
		m_lpMouseDevice8->Release();
	}
	m_lpMouseDevice8 = NULL;

	if(m_lpDInput8)
	{
		m_lpDInput8->Release();
	}
	m_lpDInput8 = NULL;

	return true;
}

bool DirectInput::IsKeyDown(int iKeyFlag)
{
	return ((m_keyState[iKeyFlag] & 0x80) == 0x80)?true:false;
}

bool DirectInput::IsKeyUp(int iKeyFlag)
{
	return true;
}

bool DirectInput::MouseMove(int& iX,int& iY)
{
	return true;
}

bool DirectInput::MouseLButtonDown()
{
	return ((m_kMouseState.rgbButtons[MOUSE_LEFT_BUTTON] & 0x80) == 0x80?true:false);
}

bool DirectInput::MouseLButtonUp()
{
	return true;
}

bool DirectInput::MouseLButtonDClick()
{
	return true;
}

bool DirectInput::MouseRButtonDown()
{
	return ((m_kMouseState.rgbButtons[MOUSE_RIGHT_BUTTON] & 0x80) == 0x80)?true:false;
}

bool DirectInput::MouseRButtonUp()
{
	return true;
}

bool DirectInput::MouseRButtonDClick()
{
	return true;
}